<template>
  <!-- 新增对话框 -->
  <el-dialog
    :visible.sync="pwdVisible"
    width="40%"
    :before-close="handleClose"
  >
    <el-form :model="pwdData" :rules="rules" ref="ruleForm" label-width="100px" style="margin-right: 50px;">
      <h1><i class="el-icon-lock"/> 重置用户密码 </h1>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="pwdData.password" clearable show-word-limit maxlength="20"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="pwdData.confirmPassword" maxlength="20" show-word-limit clearable/>
      </el-form-item>
      <el-form-item>
        <p class="el-icon-info"> 建议重置密码为 6个9 </p>
      </el-form-item>
      <el-form-item align="right">
        <el-button v-permission="'user:password'" @click="cancel('ruleForm')">取消</el-button>
        <el-button v-permission="'user:password'" @click="resetForm('ruleForm')">重置</el-button>
        <el-button v-permission="'user:password'" type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import { updatePwd } from '@/api/user'

export default {
  props: ['pwdData', 'pwdVisible'],
  data() {
    // 校验新密码和确认密码是否一致
    const validateCfPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.pwdData.password) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validateCfPass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭窗口
    handleClose() {
      this.$refs['ruleForm'].resetFields()
      this.$emit('closeUpdatePwdDialog')
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 取消
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.$emit('closeUpdatePwdDialog')
    },
    // 提交表单
    async submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const response = await updatePwd(this.pwdData)
          if (response.code === 200) {
            this.$message.success(response.message)
            this.handleClose()
            // 刷新数据列表
            this.$emit('fetchData')
          } else {
            this.$message.error(response.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
h1 {
  text-align: center;
  margin-bottom: 50px;
}
</style>
